package com.sc.nft.sup;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

@NoArgsConstructor
@Data
public class MetaPage<T> implements Serializable {
  private static final long serialVersionUID = 4920883416482893223L;
  protected long currentPage;
  protected long totalCount;
  protected long pageSize;
  private Collection<T> data;

  public MetaPage(IPage<T> data) {
    if (ObjectUtil.isNotNull(data)) {
      this.data = data.getRecords();
      this.currentPage = data.getCurrent();
      this.pageSize = data.getSize();
      this.totalCount = data.getTotal();
    }
  }

  public MetaPage(Collection<T> data, IPage<?> page) {
    this.data = data;
    this.currentPage = page.getCurrent();
    this.pageSize = page.getSize();
    this.totalCount = page.getTotal();
  }

  public MetaPage(long currentPage, long pageSize) {
    this.currentPage = currentPage;
    this.pageSize = pageSize;
  }

//  public static <T> MetaPage<T> empty(PageReq req) {
//    return new MetaPage<>(req.getPageNo(), req.getPageSize());
//  }

  public static <T> MetaPage<T> success() {
    return new MetaPage<>(null);
  }

  public static <T> MetaPage<T> success(IPage<T> o) {
    return new MetaPage<>(o);
  }

  public static <T> MetaPage<T> success(Collection<T> data, IPage<?> page) {
    return new MetaPage<>(data, page);
  }

  public static <T> MetaPage<T> success(IPage<?> o, Class<T> clazz) {
    return copyListPage(o, clazz);
  }

  public static <T> MetaPage<T> fail() {
    return new MetaPage<>(null);
  }

  public static <T> MetaPage<T> copyListPage(IPage<?> source, Class<T> listType) {
    Assert.notNull(source, "Source must not be null");
    Assert.notNull(listType, "listType must not be null");
    Page<T> page = new Page<>();
    page.setCurrent(source.getCurrent());
    page.setTotal(source.getTotal());
    List<?> origin = source.getRecords();
    if (CollectionUtils.isEmpty(origin)) {
      return MetaPage.success(page);
    }
    BeanUtil.copyProperties(source, page, "records");
    List<T> targetList = BeanUtil.copyToList(origin, listType);
    page.setRecords(targetList);
    return MetaPage.success(page);
  }
}
